package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.dao.GoodsCartDao;
import com.lcf.system.dto.GoodsCartDTO;
import com.lcf.system.entity.GoodsCart;
import com.lcf.system.service.GoodsCartService;
import com.lcf.system.vo.GoodsCartVO;
import com.lcf.system.vo.GoodsRelationVO;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 购物车(GoodsCart)表服务实现类
 *
 * @author lcf
 * @since 2025-04-24 21:14:34
 */
@Service("goodsCartService")
public class GoodsCartServiceImpl extends ServiceImpl<GoodsCartDao, GoodsCart> implements GoodsCartService {

    @Override
    public boolean insert(GoodsCartDTO dto) {
        String openId = UserUtils.getOpenId();
        GoodsCart goodsCart = Db.lambdaQuery(GoodsCart.class)
                .eq(GoodsCart::getOpenId, openId)
                .eq(GoodsCart::getGoodsId, dto.getGoodsId())
                .one();

        if (goodsCart != null) {
           return Db.lambdaUpdate(GoodsCart.class)
                    .set(GoodsCart::getGoodsNum, goodsCart.getGoodsNum() + dto.getGoodsNum())
                    .eq(GoodsCart::getId, goodsCart.getId())
                    .update();
        }

        goodsCart = BeanUtil.copyProperties(dto, GoodsCart.class);
        goodsCart.setOpenId(openId);

        return goodsCart.insert();
    }

    @Override
    public boolean update(long id, GoodsCartDTO dto) {
        GoodsCart goodsCart = BeanUtil.copyProperties(dto, GoodsCart.class);
        goodsCart.setId(id);
        return goodsCart.updateById();
    }

    @Override
    public boolean delete(long id) {
        return removeById(id);
    }

    @Override
    public GoodsCartVO query(long id) {
        GoodsCart goodsCart = getById(id);
        if (goodsCart == null) {
            throw new SysException("购物车不存在");
        }

        GoodsCartVO goodsCartVO = BeanUtil.copyProperties(goodsCart, GoodsCartVO.class);
        GoodsRelationVO goodsVO = new GoodsRelationVO();
        goodsVO.setId(goodsCart.getGoodsId());
        goodsCartVO.setGoods(goodsVO);
        return goodsCartVO;
    }

    @Override
    public List<GoodsCartVO> myList() {
        List<GoodsCart> list = Db.lambdaQuery(GoodsCart.class).eq(GoodsCart::getOpenId, UserUtils.getOpenId()).list();
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }

        List<GoodsCartVO> goodsCart = BeanUtil.copyToList(list, GoodsCartVO.class);
        goodsCart.forEach(x -> {
            GoodsRelationVO goodsVO = new GoodsRelationVO();
            goodsVO.setId(x.getGoodsId());
            x.setGoods(goodsVO);
        });

        return goodsCart;
    }
}

